$(()=>{
  let $width          = $('#width'),
      $height         = $('#height'),
      $btnCal         = $('#calc'),
      $form           = $('#main'),
      $perimeter      = $('#perimeter'),
      $widthValidate  = $('#width-validate'),
      $heightValidate = $('#height-validate'),
      $area           = $('#area');

//  $form.focusout((e)=>{
//    console.log(e.target);
//  })


  $width.focusout(()=>{
    if(!validate($width,$widthValidate)){
      $width.select();
    }
  });

  $height.focusout(()=>{
    if(!validate($height,$heightValidate)){
      $height.select();
    };
  })

  $btnCal.click(()=> {
    let w = Number($width.val()),
        h = Number($height.val());

    if(validate($width, $widthValidate) && validate($height,$heightValidate)){
      let p = (w + h) * 2;
      let a = w * h;
      function roundFractional(x, n) {
        return Math.round(x * Math.pow(10, n)) / Math.pow(10, n);
      }                                                             
      $perimeter.val(roundFractional(p,2));
      $area.val(roundFractional(a,2)); 
    }
  })
})

function validate(input, output) {
  if(input.val() === '') {
    output.html('该字段不能为空');
    return false;          
  } else {
    output.html('');      
  }

  let val = Number(input.val());

  if(isNaN(val)) {
    output.html('该字段应该是数值');
    return false;          
  } else {
    output.html('')         
  }

  if(val < 0) {
    output.html('该数值不能小于零');
    return false;         
  } else {
    output.html('');   
  }
  return true
}
